<script setup>
import {ElMessage} from 'element-plus';
import {ref} from "vue";
import {userRegisterService, sendCodeService} from "@/api/account/account.js";
import {useRouter} from "vue-router";

const router = useRouter();

const formData = ref({
  phone: "",
  username: "",
  password: "",
  confirmPassword: "",
  code: ""
});

const countDown = ref(0);
const isCounting = ref(false);

const formRef = ref(); // 表单引用

// 获取短信验证码
const getSmsCode = async () => {
    await sendCodeService();
    ElMessage.success('已获取授权码');
    isCounting.value = true;
    countDown.value = 60;
    const timer = setInterval(() => {
      countDown.value--;
      if (countDown.value <= 0) {
        clearInterval(timer);
        isCounting.value = false;
      }
    }, 1000);
};

// 调用后台接口，完成注册
const register = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
        await userRegisterService(formData.value);
        ElMessage.success('注册成功');
        await router.push('/login');
    } else {
      ElMessage.error('请检查注册信息');
    }
  });
};

// 表单验证规则
const rules = ref({
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {len: 6, message: '验证码长度必须为6位', trigger: 'blur'}
  ],
  username: [
    {required: true, message: '请输入名称', trigger: 'blur'},
    {
      pattern: /^(?!\d)[\u4e00-\u9fa5_a-zA-Z0-9]{2,20}$/,
      message: '名称格式不正确，必须是2-20位中文、英文、数字或下划线，且首字符不能是数字',
      trigger: 'blur'
    }
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*]{8,20}$/,
      message: '密码格式不正确，必须是8-20位，含字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {required: true, message: '请确认密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请确认密码'));
        } else if (value !== formData.value.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});
</script>

<template>
  <div class="login-page">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="login-title">注册</span>
      </div>
      <br>
      <div class="login-form">
        <el-form :model="formData" :rules="rules" ref="formRef">
          <el-form-item prop="code">
            <div class="sms-code-container">
              <el-button style="width: 180px;" :disabled="isCounting" @click="getSmsCode" type="primary">
                {{ countDown ? `${countDown}秒后重试` : '向管理员申请授权码' }}
              </el-button>
              <el-input  type="text" v-model="formData.code" placeholder="请输入授权码"></el-input>
            </div>
          </el-form-item>

          <el-form-item prop="username">
            <el-input type="text" v-model="formData.username" placeholder="请输入用户名称"></el-input>
          </el-form-item>
          <el-form-item prop="phone">
            <el-input type="text" v-model="formData.phone" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" v-model="formData.password" placeholder="请输入密码"></el-input>
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input type="password" v-model="formData.confirmPassword" placeholder="请确认密码"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button style="width: 100%;" type="primary" @click="register">注册</el-button>
          </el-form-item>
          <el-link type="info" @click="router.push('/login')">
            ← 返回
          </el-link>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.login-page {
  background-image: url('@/assets/images/background.jpg');
  background-size: cover;
  background-position: center;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-title {
  font-size: 20px;
  text-align: center;
}

.box-card {
  width: 500px;
  margin-left: 80vh;
}

.sms-code-container {
  display: flex;
  gap: 10px;
}

.sms-code-container .el-input {
  flex: 1;
}

.sms-code-container .el-button {
  width: 120px;
}
</style>